﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace Shine.Util.Convertor
{
    /// <summary>
    /// 字符串操作类
    /// </summary>
    public class StringHelper
    {
        /// <summary>
        /// 去除字符串中所有连续的及前后的trimmer字符
        /// </summary>
        /// <param name="value">待处理的字符串</param>
        /// <param name="trimmer">需要处理掉的字符</param>
        /// <returns>返回处理好的字符串 如果传入是空值，那么返回的也是空值</returns>
        public static string TrimWholeString(string value, char trimmer)
        {
            if (string.IsNullOrWhiteSpace(value)) return value;
            value = value.Replace(trimmer.ToString() + trimmer.ToString(), trimmer.ToString());
            value = value.Trim(trimmer);
            return value;
        }

        /// <summary>
        /// 把可能null的字符串进行处理
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string ConvertWRTNull(object o)
        {
            if (o == null)
            {
                return "";
            }
            else
            {
                return o.ToString().Trim();
            }
        }

        /// <summary>
        /// 将字符串转化成二进制
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] ToByte(string str)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            return encoding.GetBytes(str);
        }

        /// <summary>
        /// 将二进制转换成字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string FromByte(byte[] bytes)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            return encoding.GetString(bytes);
        }

        /// <summary>
        /// 通过文件名得到文件的二进制数据内容
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static byte[] GetFile(string filePath)
        {
            FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(stream);

            byte[] File = reader.ReadBytes((int)stream.Length);

            reader.Close();
            stream.Close();

            return File;
        }

        /// <summary>
        /// 将横向文本转为竖向文本
        /// </summary>
        /// <param name="text">要转换的文本</param>
        /// <returns></returns>
        public static string TextH2V(string text)
        {
            string str = ""; 
            foreach (char c in text)
            {
                if (str == "") str = c.ToString();
                else str = str + "\r\n" + c;
            }
            return str;
        }

        /// <summary>
        /// 将全角字符串转半角字符串
        /// </summary>
        /// <param name="input">任意字符串</param>
        /// <returns></returns>
        public static string ToDBC(string input)
        {
            //全角空格为12288，半角空格为32,其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new string(c);
        }

        /// <summary>
        /// 将半角字符串转全角字符串
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ToSBC(string input)
        {
            //全角空格为12288，半角空格为32,其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 32)
                {
                    c[i] = (char)12288;
                    continue;
                }
                if (c[i] < 127)
                    c[i] = (char)(c[i] + 65248);
            }
            return new string(c);
        }

        /// <summary>
        /// 计算文字长度 字母及数字为1 汉字长度为2
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int TextLength(string value)
        {
            int Count = 0;
            foreach (char a in value)
            {
                if (int.Parse(System.Text.Encoding.ASCII.GetBytes(a.ToString())[0].ToString()) >= 32
                    && int.Parse(System.Text.Encoding.ASCII.GetBytes(a.ToString())[0].ToString()) <= 127)
                {
                    Count++;
                }
                else
                {
                    Count = Count + 2;
                }
            }
            return Count;
        }

        /// <summary>
        /// 判断一个字符串内是否既有全角又有半角
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool DSALL(string value)
        {
            bool hasD = false;
            bool hasS = false;
            foreach (char a in value)
            {
                if (int.Parse(Encoding.ASCII.GetBytes(a.ToString())[0].ToString()) >= 32 && int.Parse(Encoding.ASCII.GetBytes(a.ToString())[0].ToString()) <= 127)
                {
                    hasD = true;
                    if (hasS) return true;
                }
                else
                {
                    hasS = true;
                    if (hasD) return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 去处字符串中指定的字符
        /// </summary>
        /// <param name="text"></param>
        /// <param name="c"></param>
        /// <returns></returns>
        public static string RemoveChar(string text, char c)
        {
            string rst = "";
            foreach (char item in text)
            {
                if (item != c)
                    rst = rst + item;
            }
            return rst;
        }

        /// <summary>
        /// GetChineseSpell方法:取得汉字字符串的拼音的首字母
        /// </summary>
        static public string GetShortAlias(string strText)
        {
            int len = strText.Length;
            string myStr = "";
            for (int i = 0; i < len; i++)
            {
                myStr += getSpell(strText.Substring(i, 1));
            }
            return myStr;
        }

        /// <summary>
        /// getSpell方法:取得汉字字符的拼音的首字母
        /// </summary>
        public static string getSpell(string cnChar)
        {
            byte[] arrCN = Encoding.Default.GetBytes(cnChar);
            if (arrCN.Length > 1)
            {
                int area = (short)arrCN[0];
                int pos = (short)arrCN[1];
                int code = (area << 8) + pos;
                int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 };
                for (int i = 0; i < 26; i++)
                {
                    int max = 55290;
                    if (i != 25) max = areacode[i + 1];
                    if (areacode[i] <= code && code < max)
                    {
                        return System.Text.Encoding.Default.GetString(new byte[] { (byte)(65 + i) });
                    }
                }
                return "*";
            }
            else 
                return cnChar;
        }

        /// <summary>
        /// IsContainDFX方法:判断是否包含地方字
        /// </summary>
        /// <param name="strText"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <returns></returns>
        public static bool IsContainDFX(string strText, string charset)
        {
            int len = strText.Length;
            for (int i = 0; i < len; i++)
            {
                System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);

                byte[] arrCN = chs.GetBytes(strText.Substring(i, 1));
                if (arrCN.Length > 1)
                {
                    int area = (short)arrCN[0];
                    int pos = (short)arrCN[1];
                    int code = (area << 8) + pos;

                    if (((code > 0xAAA0) && (code < 0xAFFE)) || ((code > 0xF8A1) && (code < 0xFEFE)) || ((code > 0xA140) && (code < 0xA7A0)))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// 判断一个字符串是否可以转变成一个正小数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        /// <author>sheng</author>
        static public bool CanConvert2PositiveDouble(object str)
        {
            string pattern = @"^[+]?\d+(\.\d+)?$";
            return Regex.IsMatch(ConvertWRTNull(str), pattern);
        }

        /// <summary>
        /// 判断一个字符串是否可以转变成一个小数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        /// <author>sheng</author>
        static public bool CanConvert2Double(object str)
        {
            string pattern = @"^[+|-]?\d+(\.\d+)?$";
            return Regex.IsMatch(ConvertWRTNull(str), pattern);
        }

        /// <summary>
        /// 判断一个字符串是否可以转变成一个正整数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        /// <author>sheng</author>
        static public bool CanConvert2PositiveInt(object str)
        {
            string pattern = @"^\d+$";
            return Regex.IsMatch(ConvertWRTNull(str), pattern);
        }

        /// <summary>
        /// 判断一个字符串是否可以转变成一个整数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        /// <author>sheng</author>
        public static bool CanConvert2Int(object str)
        {
            string pattern = @"^[+|-]?\d+$";
            return Regex.IsMatch(ConvertWRTNull(str), pattern);
        }

        /// <summary>
        /// 判断一个经纬度字符串是否符合“×°×′×.×″”格式
        /// </summary>
        /// <param name="strDMS"></param>
        /// <returns></returns>
        public static bool isDMS(string strDMS)
        {
            int indexd = 0, indexm = 0, indexs = 0;
            string sD = "", sM = "", sS = "";
            indexd = strDMS.IndexOf('°');
            indexm = strDMS.IndexOf('′');
            indexs = strDMS.IndexOf('″');

            if (indexd >= 0)
            {
                sD = strDMS.Substring(0, indexd);
            }
            if (indexm >= 0)
            {
                sM = strDMS.Substring(indexd + 1, indexm - indexd - 1);
            }
            if (indexs >= 0)
            {
                sS = strDMS.Substring(indexm + 1, indexs - indexm - 1);
            }

            if (CanConvert2PositiveInt(sD) == true && CanConvert2PositiveInt(sM) == true && CanConvert2PositiveDouble(sS) == true)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 判断一个经纬度字符串是否符合“×°×′”格式
        /// </summary>
        /// <param name="strDM"></param>
        /// <returns></returns>
        public static bool isDM(string strDM)
        {
            int indexd = 0, indexm = 0;
            string sD = "", sM = "";
            indexd = strDM.IndexOf('°');
            indexm = strDM.IndexOf('′');

            if (indexd >= 0)
            {
                sD = strDM.Substring(0, indexd);
            }
            if (indexm >= 0)
            {
                sM = strDM.Substring(indexd + 1, indexm - indexd - 1);
            }

            if (CanConvert2PositiveInt(sD) == true && CanConvert2PositiveInt(sM) == true)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 通过给定的字符型字段名称，获取该字段为空的sql语句
        /// </summary>
        /// <param name="fieldname"></param>
        /// <returns></returns>
        public static string GetStringNullSql(string fieldname)
        {
            return fieldname + " is null or " + fieldname + " = '' or " + fieldname + " = ' ' or " + fieldname + " = '0'";
        }

        /// <summary>
        /// 获取给定字符型字段集合为空的sql语句
        /// </summary>
        /// <param name="fieldnames"></param>
        /// <returns></returns>
        public static string GetStringNullSql(List<string> fieldnames)
        {
            string sql = "";
            foreach (string fieldname in fieldnames)
            {
                sql += "(" + GetStringNullSql(fieldname) + ") or ";
            }

            sql = sql.TrimEnd(" or".ToCharArray());
            return sql;
        }

        /// <summary>
        /// 通过给定的数字型字段名称，获取该字段为空的sql语句，注意，这里0也认为是空
        /// </summary>
        /// <param name="fieldname"></param>
        /// <returns></returns>
        public static string GetNumericNullSql(string fieldname)
        {
            return fieldname + " is null or " + fieldname + " = 0";
        }

        /// <summary>
        /// 获取给定数字型字段集合为空的sql语句，注意，这里0也认为是空
        /// </summary>
        /// <param name="fieldnames"></param>
        /// <returns></returns>
        public static string GetNumericNullSql(List<string> fieldnames)
        {
            string sql = "";
            foreach (string fieldname in fieldnames)
            {
                sql += "(" + GetNumericNullSql(fieldname) + ") or ";
            }
            sql = sql.TrimEnd(" or".ToCharArray());
            return sql;
        }
    }
}
